<template>
  <el-dialog
    title="预订菜品"
    v-model="visible"
    width="950px"
    class="orderTop"
  >
    <div class="order-form">
      <!-- 左侧菜品选择区域 -->
      <div class="dish-select">
        <h3>选择菜品</h3>
        <div class="dish-list">
          <el-card
            v-for="dish in props.dishes"
            :key="dish.id"
            class="dish-item"
            :class="{ selected: isSelected(dish.id) }"
            @click="toggleDish(dish)"
          >
            <el-image :src="dish.image" fit="cover" class="dish-img" />
            <div class="dish-info">
              <h4>{{ dish.name }}</h4>
              <div class="price">¥{{ dish.price }}</div>
              <div v-if="isSelected(dish.id)" class="quantity-control">
                <el-input-number
                  v-model="selectedDishes[dish.id]"
                  :min="0"
                  :max="99"
                  size="small"
                  @change="(val) => handleQuantityChange(dish.id, val)"
                  @click.stop
                />
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 右侧预订信息表单 -->
      <div class="booking-form">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="预订日期" prop="date">
            <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="选择日期"
              :disabled-date="disabledDate"
            />
          </el-form-item>

          <el-form-item label="预订时间" prop="time">
            <el-time-select
              v-model="form.time"
              start="10:00"
              step="00:30"
              end="21:00"
              placeholder="选择时间"
            />
          </el-form-item>

          <el-form-item label="餐桌" prop="tableId">
            <el-select v-model="form.tableId" placeholder="请选择餐桌">
              <el-option
                v-for="table in availableTables"
                :key="table.id"
                :label="`${table.tableNumber}（${table.capacity}人桌）`"
                :value="table.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="用餐人数" prop="personCount">
            <el-input-number
              v-model="form.personCount"
              :min="1"
              :max="selectedTable ? selectedTable.capacity : 99"
            />
          </el-form-item>

          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
          </el-form-item>

          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>

        <!-- 已选菜品列表 -->
        <div class="selected-dishes">
          <h3>已选菜品</h3>
          <el-empty v-if="!selectedDishList.length" description="暂未选择菜品" />
          <template v-else>
            <div class="dish-list">
              <div v-for="dish in selectedDishList" :key="dish.id" class="dish-item">
                <span class="name">{{ dish.name }}</span>
                <span class="quantity">x{{ dish.quantity }}</span>
                <span class="subtotal">¥{{ (dish.price * dish.quantity).toFixed(2) }}</span>
              </div>
            </div>
            <div class="total">
              总计：<span class="price">¥{{ totalAmount.toFixed(2) }}</span>
            </div>
          </template>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button
        type="primary"
        :loading="loading"
        :disabled="!selectedDishList.length"
        @click="handleSubmit"
      >
        确认预订
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { createOrder } from '@/api/order'
import dayjs from 'dayjs'

const props = defineProps({
  restaurantId: {
    type: [Number, String],
    required: true
  },
  tables: {
    type: Array,
    required: true
  },
  dishes: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['success'])
const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)

// 选中的菜品Map: dishId -> quantity
const selectedDishes = ref({})

// 可用餐桌列表
const availableTables = computed(() => {
  return props.tables.filter(table => table.available)
})

// 选中的餐桌
const selectedTable = computed(() => {
  return props.tables.find(table => table.id === form.value.tableId)
})

// 已选菜品列表
const selectedDishList = computed(() => {
  return Object.entries(selectedDishes.value)
    .filter(([_, quantity]) => quantity > 0)
    .map(([dishId, quantity]) => {
      const dish = props.dishes.find(d => d.id === Number(dishId))
      return {
        ...dish,
        quantity
      }
    })
})

// 计算总金额
const totalAmount = computed(() => {
  return selectedDishList.value.reduce((total, dish) => {
    return total + (dish.price * dish.quantity)
  }, 0)
})

const form = ref({
  restaurantId: props.restaurantId,
  tableId: null,
  date: null,
  time: null,
  personCount: 1,
  contactName: '',
  contactPhone: '',
  remark: ''
})

// 表单验证规则
const rules = {
  date: [{ required: true, message: '请选择预订日期', trigger: 'change' }],
  time: [{ required: true, message: '请选择预订时间', trigger: 'change' }],
  tableId: [{ required: true, message: '请选择餐桌', trigger: 'change' }],
  personCount: [{ required: true, message: '请输入用餐人数', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 检查菜品是否已选择
const isSelected = (dishId) => {
  return selectedDishes.value[dishId] > 0
}

// 切换选择菜品
const toggleDish = (dish) => {
  if (!selectedDishes.value[dish.id]) {
    selectedDishes.value[dish.id] = 1
  }
}

// 处理数量变化
const handleQuantityChange = (dishId, quantity) => {
  if (quantity === 0) {
    delete selectedDishes.value[dishId]
  } else {
    selectedDishes.value[dishId] = quantity
  }
}

// 提交订单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    const orderData = {
      ...form.value,
      date: dayjs(form.value.date).format('YYYY-MM-DD'),
      time: form.value.time,
      orderDetails: selectedDishList.value.map(dish => ({
        dishId: dish.id,
        quantity: dish.quantity
      }))
    }

    await createOrder(orderData)
    ElMessage.success('预订成功')
    visible.value = false
    emit('success')
  } catch (error) {
    console.error('预订失败:', error)
    ElMessage.error(error.response?.data?.msg || '该时间段该餐厅的该餐桌已被预订')
  } finally {
    loading.value = false
  }
}

// 打开弹窗
const open = () => {
  visible.value = true
  form.value = {
    restaurantId: props.restaurantId,
    tableId: null,
    date: null,
    time: null,
    personCount: 1,
    contactName: '',
    contactPhone: '',
    remark: ''
  }
  selectedDishes.value = {}
}

defineExpose({
  open
})
</script>

<style scoped lang="scss">



.order-form {
  display: flex;
  gap: 20px;
  height: 700px;
}

.dish-select {
  flex: 1;
  border-right: 1px solid #eee;
  padding-right: 20px;
  overflow-y: auto;

  h3 {
    margin: 0 0 20px;
    font-size: 18px;
  }

  .dish-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .dish-item {
    cursor: pointer;
    transition: all 0.3s;
    border: 2px solid transparent;

    &:hover {
      transform: translateY(-2px);
    }

    &.selected {
      border-color: var(--el-color-primary);
    }

    .dish-img {
      width: 100%;
      height: 120px;
      object-fit: cover;
    }

    .dish-info {
      padding: 10px;

      h4 {
        margin: 0 0 8px;
        font-size: 16px;
      }

      .price {
        color: #f56c6c;
        font-size: 16px;
        font-weight: bold;
      }

      .quantity-control {
        margin-top: 8px;
      }
    }
  }
}

.booking-form {
  flex: 1;
  overflow-y: auto;
}

.selected-dishes {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;

  h3 {
    margin: 0 0 15px;
    font-size: 16px;
  }

  .dish-list {
    .dish-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px dashed #eee;

      .name {
        flex: 1;
      }

      .quantity {
        margin: 0 15px;
        color: #666;
      }

      .subtotal {
        color: #f56c6c;
        font-weight: bold;
      }
    }
  }

  .total {
    margin-top: 15px;
    text-align: right;
    font-size: 16px;

    .price {
      color: #f56c6c;
      font-size: 20px;
      font-weight: bold;
    }
  }
}
</style>
